package com.snowflake.ecatalog.web.account;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.google.common.collect.Maps;
import com.snowflake.ecatalog.entity.Profile;
import com.snowflake.ecatalog.service.account.ShiroDbRealm.ShiroUser;
import com.snowflake.ecatalog.service.admin.ProfileService;
import com.snowflake.ecatalog.util.LoginUtil;

/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，

 * 真正登录的POST请求由Filter完成,
 * 
 */
@Controller
@RequestMapping(value = "/login")
public class LoginController {

	@Autowired
	private ProfileService profileService;
	
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String login() {
		return "account/login";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String fail(@RequestParam(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM) String userName, Model model) {
		model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, userName);
		return "account/login";
	}
	
	@RequestMapping(value = "success")
	public String success(ServletRequest request,HttpSession session) {
		//放置profileId到session中
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		if(user.roles.indexOf("user") >= 0){
			Long profileId = LoginUtil.getProfileIdFromSession(session);
			if(profileId == null){
				Map<Long, String> profiles = getProfileSelect(user.id);
				session.setAttribute("PROFILE_SELECT", profiles);
				if(profiles.size() > 0){
					profileId = profiles.keySet().iterator().next();
					session.setAttribute("PROFILE_ID", profileId);
				}
			}
			return "redirect:/startup/";
		}else if(user.roles.indexOf("admin") >= 0){
			return "redirect:/standard/";
		}else {
			return "account/login";
		}
	}
	
	private Map<Long, String> getProfileSelect(Long userId){
		Map<Long, String> profiles = Maps.newLinkedHashMap();
		List<Profile> profileList = profileService.getEnableProfilesOfUser(userId);
		for (Profile p : profileList) {
			profiles.put(p.getId(), p.getName());
		}
		return profiles;
	}

}
